package logic

import (
	"context"
	"errors"
	"user_src/models"
	"user_src/pkg"

	"user_src/internal/svc"
	"user_src/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealnameAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealnameAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealnameAuthLogic {
	return &RealnameAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealnameAuthLogic) RealnameAuth(in *user.RealnameAuthRequest) (*user.RealnameAuthResponse, error) {
	// todo: add your logic here and delete this line

	//先判断是否已认证
	var err error
	var ur models.UserRealname
	ur.UserId = int(in.UserId)

	if err = ur.GetUserRealnameByUserId(); err != nil {
		logx.Error("查询用户实名信息失败:", err)
		return nil, err
	}

	//实名已存在
	if ur.ID != 0 {
		logx.Error("用户已实名")
		return nil, errors.New("用户已实名")
	}

	//调用第三方接口进行认证
	if !pkg.RealnameAuth(in.IdCard, in.Realname) {
		logx.Error("实名认证失败")
		return nil, errors.New("实名认证失败")
	}

	//保存认证信息
	ur.Realname = in.Realname
	ur.IdCard = in.IdCard
	if err = ur.Create(); err != nil {
		logx.Error("保存用户实名信息失败:", err)
		return nil, err
	}

	return &user.RealnameAuthResponse{}, nil
}
